package com.sinosoft.utils.finance;

import java.math.BigDecimal;

/**
 * @Auther: zouren
 * @Date: 2019/4/23 17:34
 * @Description:
 */
public class PMTUtil {

    public static double pmtRoundDown(
            double monthRate,
            int periods,
            double amount) {

        double var = Math.pow(1 + monthRate, periods);
        double pmtAmount = amount * (monthRate * var) / (var - 1);
        return new BigDecimal(pmtAmount).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();


    }

    /**
     *
     * @param monthRate 月利率
     * @param periods 期数
     * @param amount
     * @param percise 保留数
     * @return
     */
    public static double PMT(
            double monthRate,
            int periods,
            double amount,
            int percise) {

        double var = Math.pow(1 + monthRate, periods);//求x的y次方
        double pmtAmount = amount * (monthRate * var) / (var - 1);
        return new BigDecimal(pmtAmount).setScale(percise, BigDecimal.ROUND_HALF_UP).doubleValue();


    }


    //参考https://support.office.com/zh-CN/article/PV-%E5%87%BD%E6%95%B0-23879D31-0E02-4321-BE01-DA16E8168CBD

    public static double pv(double monthRate, int periods, double peridsAmount) {


        /**
         *如果年化收益率为零,monthRate作分母会出现NaN错误,需要对月利率为零进行特殊处理
         */
        if (monthRate == 0) {
            return periods * peridsAmount;
        }


        double var = Math.pow(1 + monthRate, -periods);
        double pvAmount = (peridsAmount - peridsAmount * var) / monthRate;//double pvAmount =（1+ monthRate * type）*（peridsAmount - peridsAmount * var）/ monthRate;
        return new BigDecimal(pvAmount).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }


    public static void main(String[] args) {

        System.out.println(PMT(0.115 / 12, 12, 10000, 2));

        System.out.println(PMTUtil.pv(0.08 / 12, 5, 662.12));

    }

}
